package com.runa.rccprotocol.analysis;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.monitor.comm.entity.CommNetEquipment;
import com.runa.persistence.RepositoryServicePersis;
import com.runa.protocol.analysis.ShellBufferAnalysis;
import com.runa.protocol.dto.DtuReport;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.runa.RunaConcenAffirmDeny;
import com.runa.rccprotocol.dto.runa.RunaConcenResponseData;
import com.runa.rccprotocol.dto.thtf.THTFReportAck;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class THTFAnalysis extends ShellBufferAnalysis<byte[]> {


    public THTFAnalysis() {
        super(null, 0);
    }

    @Override
    public int fill(byte[] data, int size, String n) {
        if ("BEAT".equals(new String(data, 0, 4))) {
            interData = new DtuReport(netEquNo);
            return size - 4;
        }
        int begin;
        boolean findBegin = false;
        if ((data[0] & 0xff) == 0x38 && (data[1] & 0xff) == 0x36) {//imei
            netEquNo = new String(data, StandardCharsets.US_ASCII).replaceAll("[^0-9]", "");
            netEquNo = netEquNo.substring(0, 15);
        }
        for (begin = 0; begin < size; begin++) {
            int i = data[begin] & 0xff;
            if (i == 0x68) {
                findBegin = true;
                break;
            }
        }
        if (!findBegin) {
            return 0;
        }
        int deviceType = data[begin + 3] & 0xff;
        switch (deviceType) {
            case 0x31:
                //注册包
                int length = data[begin + 2] & 0xff;
                int checkValue = ByteUtil.sum(data, begin + 1, 13);
                if (checkValue != data[begin + length - 2]) {
                    return 0;
                }
                byte[] bytes = new byte[6];
                System.arraycopy(data, 4, bytes, 0, 6);
                String mac = ByteUtil.byteToHexString(bytes);
                //mac存入数据库
                RepositoryServicePersis.setCommNetEquipmentOnMac(netEquNo, mac);
                DtuReport dtuReport = new DtuReport(netEquNo);
                dtuReport.setMustAck(true);
                dtuReport.setAck(new THTFReportAck(mac));
                interData = dtuReport;
                break;
            case 0x30:
                //心跳
                length = data[begin + 2] & 0xff;
                checkValue = ByteUtil.sum(data, begin + 1, length - 3);
                if (checkValue != data[begin + length - 2]) {
                    return 0;
                }
                bytes = new byte[6];
                System.arraycopy(data, 4, bytes, 0, 6);
                mac = ByteUtil.byteToHexString(bytes);
                if (netEquNo == null) {
                    CommNetEquipment equipment = RepositoryServicePersis.getCommNetEquipmentOnMac(mac);
                    netEquNo = equipment.getSerial();
                }
                dtuReport = new DtuReport(netEquNo);
                interData = dtuReport;
                break;
            case 0x34:
                length = data[begin + 2] & 0xff;
                if (size - length < 10) {
                    return -10;
                }
                checkValue = ByteUtil.sum(data, 1, length - 3);
                if (checkValue != data[begin + length - 2]) {
                    return 0;
                }
                ValveVO valveVO = new ValveVO();
                handleValveData(data, begin, valveVO);
                break;
            case 0x35:
                length = data[begin + 2] & 0xff;
                checkValue = ByteUtil.sum(data, 1, length - 3);
                if (checkValue != data[begin + length - 2]) {
                    return 0;
                }
                this.interData = new RunaConcenResponseData();
                break;
            default:
                interData = null;
        }
        return 0;
    }

    private void handleValveData(byte[] data, int index, ValveVO valveVO) {
        index += 14;
        //集中器时间  使用热表时间
        String serialNo = ByteUtil.byteToHexString(data, index, 6);
        index += 6;
        valveVO.setValveSerial(serialNo);
        //信息类型
        int datum = data[index];
        if (datum == 2) {//为控制应答短数据
            this.interData = new RunaConcenAffirmDeny(true);
            return;
        }
        index += 5; //新阀协议
        ++index;
        //自检测命令
        ++index;
        double open = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setActOpen((float) open);
        double temperatureSupply = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setSupplyTemp((float) temperatureSupply);
        double temperatureReturn = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setReturnTemp((float) temperatureReturn);
        double pressureSupply = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setSupplyPre((float) pressureSupply);
        double returnPressure = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setReturnPre((float) returnPressure);
        double feedbackOpening = ByteUtil.byteToShort(data, index, ByteOrder.AB) * 0.1;
        index += 2;
        valveVO.setRemoteSet((float) feedbackOpening);
//        //无单位,累计工作时间
//        int openTime = ByteUtil.bcdToInt(data, index, 3, false);
//        meterData.setWorkTime(openTime);
//        index+=3;
//        try {
//            meterData.setMeterDate((new SimpleDateFormat("yyyyMMddHHmmss").parse(ByteUtil.bcd2str(data, index, 7, false))));
//        } catch (ParseException e) {
//            
//        }
        valveVO.setValveDate(new Date());
        valveVO.setReadTime(new Date());
        RunaConcenResponseData responseData = new RunaConcenResponseData();
        responseData.addRepData(valveVO);
        interData = responseData;
    }

    public static void main(String[] args) {
        THTFAnalysis analysis = new THTFAnalysis();
//        String s = "68 95 62 07 16 08 21 68 91 08 33 33 33 33 45 33 33 33 50 16".replace(" ","");
        //imei
//        String s = "38 36 39 34 36 35 30 35 36 32 32 36 35 30 34";
//        String s = "38363835353830363436343137343768001031151D6F94E5FC001112078116";
        String s = "68003334F0C5B7F598380007FF99B28C8BCEEA615500010007010003E8000000430000000003E80000006423DB2F4F0601771668000A35000000014016";
//        String s = "38 36 38 35 35 38 30 36 34 36 33 39 32 36 31";
//        String shang = "68 00 10 31 B8 2A 9E 63 2B 71 01 00 12 03 D6 16";
//        String heart = "68 00 10 31 B8 2A 9E 63 2B 71 01 00 12 03 D6 16";
//        String heatMeter = "68 00 26 34 B8 2A 9E 63 2B 71 00 0A FF B9 92 EE EA C3 1F 74 01 00 03 20 00 00 00 D4 00 00 00 00 03 22 00 00 78 16";
        byte[] bytes = ByteUtil.hexStringToByte(s);
//        byte[] bytes = s.getBytes();
        analysis.fill(bytes, bytes.length, "");
        System.out.println(JSON.toJSONString(analysis.gain()));

//        int i = DigitalUtil.calcCrc16(ByteUtil.hexStringToByte("7E 0D 68 34 20 11 10 0F 1E 07 12 A5 5A D8 8D 7E".replace(" ","")), 1, 12);
//        int i = DigitalUtil.CRC16_XMODEM(ByteUtil.hexStringToByte("0D 68 34 20 11 10 0F 1E 07 12 A5 5A"));
//        System.out.println(i);
    }
}
